/**
 * @file models/fundPool.js
 * 基金池
 * @author
 */

 import { routerRedux } from 'dva/router';
 import api from '../api';
 import { Arrayremoval } from '../utils/helper';
 import { treeKpi } from '../routes/fundScreening/component/treeKpi';
 import Mock from 'mockjs';
/**
 * statusS [状态kpi]
 * investStrategy [投资策略kpi]
 * lPortId [搜索产品id]
 * tableList [表格数据]
 * kpiNameList [指标key数组]
 * columnKpi [表格表头]
 * checkkpi:[方案设置,选择指标数组],
 * sfkpiName [方案设置,获取kpi数组]
 * groupNumber [分组id]
 * groupNumberID [选择加入分组编号id]
 */
 export default {
    namespace: "fundpool",
    state:{
      schemeName:'',
      statusS:[],
      investStrategy:[],
      tableList:[],
      kpiNameList:[],
      columnKpi:['productName','fundCode', 'unitnav', 'fundManager', 'investStrategy', 'sharpeRatio', 'annulVolatility'],
      checkkpi:[],
      sfschemeid:"",
      sfschemename:"",
      groupNumberID:[],
      schemeId:'',//方案id
      selectedRowKeys:[],//表格数据选择
      tableData:[],//表格数据
      selectKpiList:[],//页面展示kpi指标列表
      timeRange:'7',
      beginDate:'',
      endDate:'',
      pageSize:10,
      current:1,
      pdtsearchId:'',//产品模糊搜索id
      ListPdt:[],//检索出下拉数据
      isShow:true,
      benchmark:'',
      lPortId:'',//产品id
      establish:'',//成立年限
      fundS:'',//基金规模
      invest:'',//投资策略
      statusSs:'',//状态
    },
   subscriptions:{
     setup({dispatch,history}) {
       history.listen(({pathname,query}) => {
        console.log('22222',query)
         if( pathname === '/fundScreen/fundPool' ){
            if(_.isEmpty(query)){
              dispatch({
                type: 'getFilter',
              })
              dispatch({
                type:'getAllKpiData',
              })
              dispatch({
                type:'getSchemekpi',
                payload:{
                  schemeId:1,
                }
              })
               dispatch({
                type: 'getPolicyGroup'
              })
              dispatch({
                type:'getBPdtList',
                payload:{
                  productType:'JIZHUN'
                }
              })
              dispatch({
                type:'getListPdt',
                payload:{
                  'productType':'SIMU'
                }
              })
            }else{
              dispatch({
    						type: 'whetherRequest',
    						payload: query
    					})
  			    }
          }
       })
     }
   },
   effects:{
     * whetherRequest({payload}, {call, put,select}) {
 				console.log("whetherRequest>>>",payload);
        const state=yield select(state => state.fundpool)
        const countRange = state.timeRange;
        const beginDate = state.beginDate;
        const endDate = state.endDate;
        const benchId = state.benchmark;
        const schemeId =payload.schemeId;
        console.log('whetherRequest>',countRange,beginDate,endDate,benchId,state)

        if( benchId == ''){
          yield put({
            type:'getFilter'
          })
          yield put({
            type:'getSchemekpi',
            payload:{
              schemeId:schemeId,
            }
          })
          yield put({
            type:'getAllKpiData',
          })
          yield put({
            type:'getBPdtList',
            payload:{
              productType:'JIZHUN'
            }
          });
          yield put({
            type:'getListPdt',
            payload:{
              'productType':'SIMU'
            }
          })
        }
 		},
    * getPdtList({payload},{call,put}){
      const response = yield call(api.construction.getPdtList, payload);
      console.log('getPdtList>>>',response)
      const productList = response.data.map((item, i) => ({
        id: item.productId + '',
        value: `${item.productCode}：${item.productName}`
      }))
      yield put({
        type: 'getPdtListSuccess',
        payload:productList ,
      });
    },
    * getBPdtList({payload},{call,put}){
      const response = yield call(api.construction.getPdtList, payload);
      console.log('getPdtList>>>',response)
      yield put({
        type: 'getBPdtListSuccess',
        payload:response ,
      });
    },
    * getPolicyGroup({ payload }, { call, put ,select}) {
       console.log("getPolicyGroup>>>",payload  );
        const response = yield call(api.getPolicyGroup, payload);
        const state=yield select(state => state.myattention);
        console.log("getPolicyGroup>>",state.del);
        if(state.del == true){
          state.username = ''
          state.groupName = ''
        }

        yield put({
          type: 'getPolicyGroupSuccess',
          payload: { response },
        });
      },

     * getPolicyGroup({ payload }, { call, put,select }) {
        const response = yield call(api.getPolicyGroup, payload);
        yield put({
          type: 'getPolicyGroupSuccess',
          payload: { response },
        });
      },
     * pdtSelect({ payload }, { call, put }) {
        // const state=yield select(state => state.fundpool)
			  const response = yield call(api.pdtSelect, payload);

			  yield put({
				  type: 'pdtSelectSuccess',
				  payload: { response },
			  });
		  },
     * getFilter({payload},{call,put}) {
        const response = yield call(api.getFilter, payload);
          yield put({
            type: 'getFilterSuccess',
            payload: response ,
          });
      },
      * getAllKpiData({payload},{call,put}) {
         const response = yield call(api.getAllKpiData, payload);
           yield put({
             type: 'getAllKpiDataSuccess',
             payload: response ,
           });
       },
       * getSchemekpi({payload},{select,call,put}){
  			const schemeId = payload.schemeId
  			const response = yield call(api.getSchemekpi,schemeId);
        const state=yield select(state => state.fundpool)
        yield put({
        	type:'setState',
        	payload:{
        		selectKpiList:[]
        	}
        })
  			yield put({
  				type: 'getSchemekpiSuccess',
  				payload: response ,
  			})
  		},
      *schemeSelect({ payload }, { call, put,select }) {
        const state=yield select(state => state.fundpool)
        console.log('state>>>',state,payload)
        const countRange = state.timeRange;
        const beginDate = state.beginDate;
        const endDate = state.endDate;
        const benchId = state.benchmark;
        if(_.isEmpty(beginDate)&&_.isEmpty(endDate)){
          var response = yield call(api.schemeSelect2,countRange,benchId,payload);
        }else{
          var response = yield call(api.schemeSelect,countRange,benchId,beginDate,endDate,payload);
        }
        const tableList = response.data
        console.log("schemeSelect>>>>>",response);
  			yield put({
  				type: 'schemeSelectSuccess',
  				payload: { response },
  			});
  		},
      *changeColumns({payload:query},{select,put}){
        console.log("onCheck>changeColumns",query);
        const state=yield select(state => state.fundpool)
        if(_.isEmpty(query)){
          query = ['productName','fundCode', 'unitnav', 'fundManager', 'investStrategy', 'sharpeRatio', 'annulVolatility']
          state.columnKpi = query
        }else{
          state.columnKpi = query
        }
        yield put({
  				type: 'setState',
  				payload:{
            fundeChangecolumns:true
          }
  			});
  		},
      *changeKpilist({payload:query},{put}){
        console.log("changeKpilist>>>>>",query)
        yield put({
          type: 'setState',
          payload:{
            selectKpiList:query.selectKpiList
          }
        });
      },
      * getSchemeFitkpi({payload},{call,put}){
  			const schemeId = payload.schemeId
  			const schemeid = schemeId
  			console.log("getSchemekpi>>>>payload",payload,schemeId);
  			const response = yield call(api.getSchemekpi,schemeId,{...payload});
  			yield put({
  				type: 'getSchemeFitKpiSuccess',
  				payload: response ,
  			})
  		},
      * addnewPlan({ payload }, { call, put }) {
  			const response = yield call(api.addnewPlan, payload);
  			yield put({
  				type: 'addSuccess',
  				payload: { response },
  			});
  			 yield put({
  					type: 'getFilter',
  				});
  		},
      * editSchemekpi({payload},{call,put}){
  			console.log("editSchemekpi>.payload",payload);
  			const response = yield call(api.editSchemekpi,payload);
  			yield put({
  				type: 'saveplanSuccess',
  				payload: response ,
  			})
        yield put({
          type:'setState',
          payload:{
            sfschemeid:"",
            sfschemename:""
          }
        })
  		},
      * joinAttention({ payload }, { call, put }) {
  			const response = yield call(api.joinAttention, payload);
        yield put({
          type:'setState',
          payload:{
            groupNumberID:[],
          }
        })
  		},
      * exportfilterData({ payload }, { call, put }) {
        console.log("sasasasa",JSON.stringify(payload));
        const param = JSON.stringify(payload)
        $.ajax({
          type: 'POST',
  				url: location.href.indexOf('localhost')>-1?'/api/fundPool/exportProduct':'/thfx/api/fundPool/exportProduct',
          contentType: "application/json;charset=utf-8",
          data:param,
          responseType: 'blob', // 表明返回服务器返回的数据类型
        }).then((res) => { // 处理返回的文件流
          const content = res;
          const type = 'text/csv; charset=utf-8';
          console.log("exportFilterPdtData>>content",content);
          const blob = new Blob([content])
          const dataTitle = Date.now();
          const fileName = `${dataTitle}.csv`;
          if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })
  		},
      * getListPdt({ payload:query }, { call, put }) {
        const response = yield call(api.getListPdt, query);
        const productList = response.data.map((item, i) => ({
          id: item.productId + '',
          value: `${item.productCode}：${item.productName}`
        }))
        yield put({
          type: 'getListPdt2Success',
          payload: productList ,
        });
      },
      *changeRouter({payload:query},{call,put}){
        yield put(routerRedux.push({
          pathname:`/fundScreening/fundPool`,
          query:{
            ...query,
          }
        }))
      },
   },

   reducers:{
       setState(state, {payload}) {
        console.log("111",payload);
         return {
           ...state,
           ...payload,
         }
       },
       getPolicyGroupSuccess(state, {payload}) {
       const {data} = payload.response
       console.log("getPolicyGroupSuccess>>>",payload.response,'111',data);
       const status=data ? true:false
       return {
         ...state,
         GroupStatus:status,
         GroupList:data,
       }
     },
       saveplanSuccess(state, action) {
    			const { payload: { response } } = action;
    				return {
    					...state,
    			};
    		},
       getSchemeFitKpiSuccess(state, {payload}) {
  			 const {data} = payload
  			 console.log("getSchemeFitKpiSuccess>>>",data);
         state.sfkpiName = data.kpiName;
  			 const status=data ? true:false
  			 return {
  				 ...state,
  					status,
  				 sfkpiName:data.kpiName,
  				 sfschemeid:data.schemeId,
  				 sfschemename:data.schemeName,
  			}
  		},
      getSchemekpiSuccess(state, {payload}) {
  			const {data} = payload
  			console.log("getSchemekpiSuccess>>>",data);
        state.kpiNameList = data.kpiName;
        state.schemeId = data.schemeId;
        state.schemeName = data.schemeName;
				for(var i = 0; i < treeKpi.length; i++){
						var obj = treeKpi[i];
						var num = obj.key;
						var isExist = true;
						for(var j = 0; j < data.kpiName.length; j++){
								var aj = data.kpiName[j];
								if(aj == num){
									state.selectKpiList.push(obj);
								}
						}
						if(!isExist){
							break;
						}
					}
  			 return {
  				 ...state,
  			}
  		},
      pdtSelectSuccess(state, {payload}) {
  			const {data} = payload.response
  			console.log("tablelist>>>",payload.response,'111',data);
        data.map((item,i)=>{
          if(item.establishAge == 0){
            item.establishAge = '1年以下';
          }else if(item.establishAge == 1){
            item.establishAge = '1-3年';
          }else if(item.establishAge == 2){
            item.establishAge = '3-5年';
          }else if(item.establishAge == 3){
            item.establishAge = '5年以上';
          }
        })
  			const Tablestatus=data ? true:false
        for(var i=0;i<data.length;i++){
          state.tableData.push(data[i]);
        }
        var newTableArr=[];
        for(let i=0;i<state.tableData.length;i++){
          if(Arrayremoval(state.tableData[i],newTableArr) ==-1){
             newTableArr.push(state.tableData[i]);
          }
        }
  			return {
  				...state,
  				Tablestatus,
          tableData:newTableArr
  		  }
  		},
      schemeSelectSuccess(state, {payload}) {
  			const {data} = payload.response
  			console.log("schemeSelectSuccess>>>",payload.response,'222',data);
  		/*	const mockData = Mock.mock({
					"data|5000":
		    	[{
		    		"productId|+1":1,
		        "fundManager":"@cname()",
		        "productName":'@float(10, 100, 0, 2)',
		        "fundCode":'@float(50, 100, 0, 2)',
		        "investStrategy":'股票多头',
		        "unitnav": '@float(60, 100, 0, 2)',
		        "establishAge":0,
		        "status":'已清盘',
		        "fundScale":'中小型',
		        "annualYieldRate":'@float(60, 100, 0, 2)',
		        "alpha":'@float(60, 100, 0, 2)',
		        "sharpeRatio":'@float(60, 100, 0, 2)',
		        "treynorRatio":'@float(60, 100, 0, 2)',
		        "informationRatio":'@float(60, 100, 0, 2)',
		        "sortinoRatio":'@float(60, 100, 0, 2)',
		        "m2":'@float(60, 100, 0, 2)',
		        "calmarRatio":'@float(60, 100, 0, 2)',
		        "var":'@float(60, 100, 0, 2)',
		        "volatility":'@float(60, 100, 0, 2)',
		        "cte":'@float(60, 100, 0, 2)',
		        "te":'@float(60, 100, 0, 2)',
		        "beta":'@float(60, 100, 0, 2)',
		        "maxDrawdown":'@float(60, 100, 0, 2)',
		      }],
				})
				const dddddd =mockData.data;
				console.log('schemeSelectSuccess?>>>',dddddd)*/
        data.map((item,i)=>{
          item.id=Date.now()
          if(item.establishAge == 0){
            item.establishAge = '1年以下';
          }else if(item.establishAge == 1){
            item.establishAge = '1-3年';
          }else if(item.establishAge == 2){
            item.establishAge = '3-5年';
          }else if(item.establishAge == 3){
            item.establishAge = '5年以上';
          }
        })
        // dddddd.map((item,i)=>{
        //   item.id=Date.now()
        //   if(item.establishAge == 0){
        //     item.establishAge = '1年以下';
        //   }else if(item.establishAge == 1){
        //     item.establishAge = '1-3年';
        //   }else if(item.establishAge == 2){
        //     item.establishAge = '3-5年';
        //   }else if(item.establishAge == 3){
        //     item.establishAge = '5年以上';
        //   }
        // })
        const Tablestatus=data ? true:false
        for(var i=0;i<data.length;i++){
          state.tableData.push(data[i]);
        }
        var newTableArr=[];
        for(let i=0;i<state.tableData.length;i++){
          if(Arrayremoval(state.tableData[i],newTableArr) ==-1){
             newTableArr.push(state.tableData[i]);
          }
        }
  			return {
  				...state,
  				Tablestatus,
          tableList:data,
          tableData:newTableArr
          // tableData:dddddd
  		 }
  		},
      getFilterSuccess(state, {payload}) {
          const {data} = payload
          console.log("getFilterSuccess>>>>>",data);
          const Homestatus=data ? true:false
          return {
            ...state,
            Homestatus,
            filterList:data,
        }
      },
      getAllKpiDataSuccess(state, {payload}) {
        const {data} = payload
        console.log("getAllKpiDataSuccess>>>>>",data,"state",state);
        const s = data.status;
        const inv = data.investStrategy;
        if(_.isEmpty(state.statusS)&&_.isEmpty(state.investStrategy)){
          for(var i =0;i<s.length;i++){
            state.statusS.push({"name":s[i],"value":s[i]})
          }
          for(var i=0;i<inv.length;i++) {
            state.investStrategy.push({"name":inv[i],"value":inv[i]});
          }
          return {
            ...state,
          }
        }else{
          return{
            ...state,
          }
        }

          // const Kpistatus=data ? true:false

      },
      addSuccess(state, action) {
  			const { payload: { response } } = action;
  			return {
  				...state,
  			};
  		},
      getPolicyGroupSuccess(state, {payload}) {
        const {data} = payload.response
        console.log("getPolicyGroupSuccess>>>",payload.response,'111',data);
        const status=data ? true:false
        return {
          ...state,
          GroupList:data,
        }
      },
      getListPdtSuccess(state,{payload}){
        const data = payload;
        return {
          ...state,
          ListPdt:data
        }
      },
      getListPdt2Success(state,{payload}){
        const data = payload;
        console.log('getListPdt2Success>1333',data)
        data.map((item,i)=>{
          if(item.id == '0'){
            data.splice(i, 1)
          }
        })
        data.map((item,i)=>{
          if(item.id == '1'){
            data.splice(i, 1)
          }
        })
        data.map((item,i)=>{
          if(item.id == '3'){
            data.splice(i, 1)
          }
        })
        data.map((item,i)=>{
          if(item.id == '4'){
            data.splice(i, 1)
          }
        })
        console.log('productList>>11',data)
        return {
          ...state,
          ListPdt2:data
        }
      },
      getBPdtListSuccess(state,{payload}){
        const data = payload.data;
        console.log('getPdtListSuccess>',payload,data)
        const newPDT = []
        data.map((item)=>{
          delete item.bondRate
          delete item.description
          delete item.effectiveDate
          delete item.futuresRate
          delete item.isIncludeCash
          delete item.origProductType
          delete item.productCode
          delete item.productType
          delete item.sharesRate
          if(item.productId !== 0){
            newPDT.push(item)
          }
        })
        console.log('getPdtListSuccess>>',newPDT)
        return {
          ...state,
          pdtList:newPDT
        }
        
      },
    }
 }
